package protocol;

import java.io.DataOutputStream;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.LinkedList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import protocol.Message;

public class ThreadWriter extends Thread {

    private DataOutputStream output = null;
    private ThreadWorker mServer;
    private List<Message> messageQueue = new LinkedList<>();

    public ThreadWriter(DataOutputStream _output, ThreadWorker _mServer) {
        this.output = _output;
        this.mServer = _mServer;
    }

    @Override
    public void run() {
        while (true) {
            String command;
            synchronized (messageQueue) {
                while (messageQueue.isEmpty()) {
                    try {
                        messageQueue.wait();
                    } catch (InterruptedException ex) {
                        Logger.getLogger(ThreadWriter.class.getName()).log(Level.INFO, null, ex);
                    }
                }
                command = messageQueue.remove(0).toString();
            }

            try {
                output.writeBytes(command.length()+"\r\n");
                output.writeBytes(command);
            } catch (IOException ex) {
                //Logger.getLogger(ThreadWriter.class.getName()).log(Level.INFO, null, ex);
                mServer.closeConnection();
                return;
            }
        }
    }

    public void queueToWrite(Message msg) {
        synchronized (messageQueue) {
            messageQueue.add(msg);
            messageQueue.notify();
        }

    }
}